package org.demo.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * UDP Server 
 * @author  
 * @date    2010-9-6
 * @file    org.demo.net.UDPServer.java
 */
public class UDPServer {
	// 客户端接收端口
	private static int port = 7152;
	// socket
	private DatagramSocket socket = null;
	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		UDPServer server = new UDPServer();
		
		String data = "这条消息来自 server.";
		server.sendMessage("localhost", data);
		
		System.out.println("-- server ok. --");
	}
	/**
	 * 构造函数
	 * @throws SocketException
	 */
	public UDPServer()throws SocketException{
		// 创建 socket
		this.socket = new DatagramSocket();
	}
	/**
	 * 发送数据
	 * @param data
	 */
	public void sendMessage(String host,String data)throws IOException{
		// 创建数据包
		DatagramPacket packet = createDataPack(host,port,data);
		// 发送数据包
		this.socket.send(packet);
	}
	/**
	 * 构造发送数据包
	 * @param host
	 * @param port
	 * @param data
	 * @return
	 */
	public DatagramPacket createDataPack(String host,int port,String data){
		DatagramPacket pack = null;
		try {
			byte[] buf = data.getBytes();
			InetAddress address = InetAddress.getByName(host);
			pack = new DatagramPacket(buf,buf.length,address,port);
		} catch(Exception e){
			throw new RuntimeException(e);
		}
		return pack;
	}

}
